import time

import allure
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from cloud_po.pages.base_page import BasePage
from cloud_po.utils.log_utils import logger


class WareHousePage(BasePage):
    __ADD_WAREHOUSE_BTN = (By.XPATH, "//span[text()='添加仓库（供应商）']")
    __WAREHOUSE_NAME = (By.CSS_SELECTOR, ".el-table__body .el-table__row>td:nth-child(2)>.cell")

    __INPUT_SEARCH_NAME = (By.XPATH, "(//*[@class='el-input__inner'])[1]")
    __SEARCH_BTN = (By.XPATH, "//*[@class='el-icon-search']/..")
    __I_KNOW = (By.CSS_SELECTOR, ".el-message-box__btns span")

    def click_add_warehouse(self):
        logger.info("点击添加仓库(供应商)按钮")
        with allure.step("点击添加仓库(供应商)按钮"):
            self.do_find(self.__ADD_WAREHOUSE_BTN).click()
            time.sleep(1)
        from cloud_po.pages.warehouse_add_page import WareHouseAddPage
        return WareHouseAddPage(self.driver)

    def get_warehouse_names(self):
        logger.info("获取所有仓库名称")
        # 等待至少一个元素文本非空（证明数据已加载）
        wait = WebDriverWait(self.driver, 20)  # 最多等 20 秒
        wait.until(
            lambda driver: any(
                elem.text.strip() != "" for elem in self.do_finds(self.__WAREHOUSE_NAME)
            )
        )
        elements = self.do_finds(self.__WAREHOUSE_NAME)
        name_list = [element.text for element in elements]
        return name_list

    def clean_data(self, name):
        logger.info("清理测试数据")
        with allure.step("清理仓库测试数据"):
            # self.do_find(By.XPATH,f"//*[text()={name}]/../..//span[text()='删除']").click()
            self.safe_click((By.XPATH, f"(//*[text()='{name}']/../..//span[text()='删除'])[2]"))
        return WareHousePage(self.driver)

    def search_warehouse(self, name):
        logger.info("根据仓库名称搜索仓库")
        with allure.step("仓库名称输入框输入搜索内容"):
            self.do_send_keys(name, self.__INPUT_SEARCH_NAME)
        with allure.step("点击查询"):
            self.do_find(self.__SEARCH_BTN).click()
        return self.get_warehouse_names()

    def close_alert(self):
        logger.info("关闭弹窗")
        self.web_locate_click(self.__I_KNOW)
        self.safe_click(self.__I_KNOW)
